package boot.spring.util;

import org.geotools.api.data.DataStore;
import org.geotools.api.data.DataStoreFinder;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.api.data.SimpleFeatureStore;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class ShpToPg {

    public static void main(String[] args) {
        // 配置参数
        String shpFilePath = "E:/工作/项目/预研/viz/rcu_point/rcu_point.shp"; // 替换为你的SHP文件路径
        String dbHost = "172.16.168.167";
        String dbPort = "5432";
        String dbName = "test";
        String dbUser = "postgres";
        String dbPassword = "pstgrs@2023";
        String schema = "public"; // 或你的自定义schema
        String tableName = "rcu_point"; // 目标表名

        try {
            // 1. 读取Shapefile文件
            File file = new File(shpFilePath);
            Map<String, Object> shpParams = new HashMap<>();
            shpParams.put("url", file.toURI().toURL());

            DataStore shpDataStore = DataStoreFinder.getDataStore(shpParams);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource shpFeatureSource = shpDataStore.getFeatureSource(typeName);

            // 2. 连接到PostgreSQL数据库
            Map<String, Object> pgParams = new HashMap<>();
            pgParams.put(PostgisNGDataStoreFactory.DBTYPE.key, "postgis");
            pgParams.put(PostgisNGDataStoreFactory.HOST.key, dbHost);
            pgParams.put(PostgisNGDataStoreFactory.PORT.key, dbPort);
            pgParams.put(PostgisNGDataStoreFactory.DATABASE.key, dbName);
            pgParams.put(PostgisNGDataStoreFactory.SCHEMA.key, schema);
            pgParams.put(PostgisNGDataStoreFactory.USER.key, dbUser);
            pgParams.put(PostgisNGDataStoreFactory.PASSWD.key, dbPassword);

            DataStore pgDataStore = DataStoreFinder.getDataStore(pgParams);

            if (pgDataStore == null) {
                throw new RuntimeException("无法连接到PostgreSQL数据库，请检查连接参数");
            }

            // 3. 创建目标表（如果不存在）
            SimpleFeatureType featureType = shpFeatureSource.getSchema();
            if (containsIgnoreCase(pgDataStore.getTypeNames(), tableName)) {
                System.out.println("表 " + tableName + " 已存在，将追加数据");
            } else {
                System.out.println("创建新表: " + tableName);
                pgDataStore.createSchema(featureType);
                // 在某些PostGIS版本中，可能需要手动重命名表
                System.out.println("表创建完成");
            }

            // 4. 获取目标表FeatureStore用于写入
            SimpleFeatureStore pgFeatureStore = (SimpleFeatureStore) pgDataStore.getFeatureSource(tableName);

            // 5. 写入数据
            SimpleFeatureCollection features = shpFeatureSource.getFeatures();
            try (SimpleFeatureIterator iterator = features.features()) {
                System.out.println("开始写入数据到PostgreSQL表...");
                pgFeatureStore.addFeatures(features);
                System.out.println("数据写入完成，共写入 " + features.size() + " 条记录");
            }

            // 6. 关闭连接
            shpDataStore.dispose();
            pgDataStore.dispose();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("导入过程中发生错误: " + e.getMessage());
        }
    }

    private static boolean containsIgnoreCase(String[] array, String value) {
        for (String item : array) {
            if (item.equalsIgnoreCase(value)) {
                return true;
            }
        }
        return false;
    }
}